package com.yuanjin.util;

import java.text.SimpleDateFormat;
import java.util.Calendar;

import android.annotation.SuppressLint;
import android.annotation.TargetApi;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Build;
import android.os.Handler;
import android.widget.DatePicker;
import android.widget.DatePicker.OnDateChangedListener;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.TimePicker;
import android.widget.TimePicker.OnTimeChangedListener;

import com.yuanjin.R;

/**
 * 日期时间选择控件 使用方法： private EditText inputDate;//需要设置的日期时间文本编辑框 private String
 * initDateTime="2012-9-3 14:44",//初始日期时间值 在点击事件中使用：
 * inputDate.setOnClickListener(new OnClickListener() {
 * 
 * @Override public void onClick(View v) { DateTimePickDialogUtil
 *           dateTimePicKDialog=new
 *           DateTimePickDialogUtil(SinvestigateActivity.this,initDateTime);
 *           dateTimePicKDialog.dateTimePicKDialog(inputDate);
 * 
 *           } });
 * 
 * @author 吴理琪
 * @version 1.0
 */
public class DateTimePickDialogUtil implements OnDateChangedListener,
		OnTimeChangedListener {
	private DatePicker datePicker;
	private TimePicker timePicker;
	private AlertDialog ad;
	private String dateTime;
	private String initDateTime;
	private Activity activity;
	private int TimeStyleType = 1;//
	public static final int TimeStyleType_Line = 1;
	public static final int TimeStyleType_Slash = 2;
	public Handler mHandler;

	/**
	 * 日期时间弹出选择框构造函数
	 * 
	 * @param activity
	 *            ：调用的父activity
	 * @param initDateTime
	 *            初始日期时间值，作为弹出窗口的标题和日期时间初始值
	 */
	public DateTimePickDialogUtil(Activity activity, String initDateTime) {
		this.activity = activity;
		this.initDateTime = initDateTime;

	}

	public DateTimePickDialogUtil(Activity activity, String initDateTime,
			int timeStyleType, Handler mHandler) {
		if (timeStyleType == TimeStyleType_Line
				|| timeStyleType == TimeStyleType_Slash) {
			this.TimeStyleType = timeStyleType;
		} else {
			this.TimeStyleType = TimeStyleType_Line;
		}
		this.mHandler = mHandler;
		this.activity = activity;
		this.initDateTime = initDateTime;

	}

	public DateTimePickDialogUtil(Activity activity, String initDateTime,
			int timeStyleType) {
		if (timeStyleType == TimeStyleType_Line
				|| timeStyleType == TimeStyleType_Slash) {
			this.TimeStyleType = timeStyleType;
		} else {
			this.TimeStyleType = TimeStyleType_Line;
		}
		this.activity = activity;
		this.initDateTime = initDateTime;

	}

	private void init(DatePicker datePicker, TimePicker timePicker) {
		Calendar calendar = Calendar.getInstance();
		if (!(null == initDateTime || "".equals(initDateTime))) {
			calendar = this.getCalendarByInintData(initDateTime);
		} else {
			initDateTime = calendar.get(Calendar.YEAR) + "-"
					+ calendar.get(Calendar.MONTH) + "-"
					+ calendar.get(Calendar.DAY_OF_MONTH) + " "
					+ calendar.get(Calendar.HOUR_OF_DAY) + ":"
					+ calendar.get(Calendar.MINUTE);
		}

		datePicker.init(calendar.get(Calendar.YEAR),
				calendar.get(Calendar.MONTH),
				calendar.get(Calendar.DAY_OF_MONTH), this);
		timePicker.setCurrentHour(calendar.get(Calendar.HOUR_OF_DAY));
		timePicker.setCurrentMinute(calendar.get(Calendar.MINUTE));
	}

	/**
	 * 弹出日期时间选择框方法
	 * 
	 * @param inputDate
	 *            :为需要设置的日期时间文本编辑框
	 * @return
	 */
	public AlertDialog dateTimePicKDialog(final TextView inputDate) {
		LinearLayout dateTimeLayout = (LinearLayout) activity
				.getLayoutInflater().inflate(R.layout.common_datetime, null);
		datePicker = (DatePicker) dateTimeLayout.findViewById(R.id.datepicker);
		timePicker = (TimePicker) dateTimeLayout.findViewById(R.id.timepicker);
		// 不能手动输入
		datePicker
				.setDescendantFocusability(DatePicker.FOCUS_BLOCK_DESCENDANTS);
		timePicker
				.setDescendantFocusability(TimePicker.FOCUS_BLOCK_DESCENDANTS);
		timePicker.setIs24HourView(true);
		init(datePicker, timePicker);
		timePicker.setOnTimeChangedListener(this);

		ad = new AlertDialog.Builder(activity)
				.setTitle(initDateTime)
				.setView(dateTimeLayout)
				.setPositiveButton("设置", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						if (TimeStyleType == TimeStyleType_Line) {
							// /***********************修改**************************/
							// datePicker.clearFocus();
							// Calendar calendar = Calendar.getInstance();
							//
							// calendar.set(datePicker.getYear(),
							// datePicker.getMonth(),
							// datePicker.getDayOfMonth(),
							// timePicker.getCurrentHour(),
							// timePicker.getCurrentMinute());
							// SimpleDateFormat sdf = new
							// SimpleDateFormat("yyyy-MM-dd HH:mm");
							// dateTime=sdf.format(calendar.getTime());
							// /*************************************************/
							inputDate.setText(dateTime);
							if (mHandler != null) {
								mHandler.sendEmptyMessage(10);
							}
						} else if (TimeStyleType == TimeStyleType_Slash) {
							inputDate.setText(dateTime.replaceAll("-", "/"));
							if (mHandler != null) {
								mHandler.sendEmptyMessage(10);
							}
						}

					}
				})
				.setNegativeButton("取消", new DialogInterface.OnClickListener() {
					public void onClick(DialogInterface dialog, int whichButton) {
						// inputDate.setText("");
					}
				}).show();

		onDateChanged(null, 0, 0, 0);
		return ad;
	}

	public void onTimeChanged(TimePicker view, int hourOfDay, int minute) {
		onDateChanged(null, 0, 0, 0);
	}

	public void onDateChanged(DatePicker view, int year, int monthOfYear,
			int dayOfMonth) {
		Calendar calendar = Calendar.getInstance();
		// datePicker.up
		calendar.set(datePicker.getYear(), datePicker.getMonth(),
				datePicker.getDayOfMonth(), timePicker.getCurrentHour(),
				timePicker.getCurrentMinute());
		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm");

		dateTime = sdf.format(calendar.getTime());
		ad.setTitle(dateTime);
	}

	/**
	 * 实现将初始日期时间2012-07-02 16:45 拆分成年 月 日 时 分 秒,并赋值给calendar
	 * 
	 * @param initDateTime
	 *            初始日期时间值 字符串型
	 * @return Calendar
	 */
	@TargetApi(Build.VERSION_CODES.GINGERBREAD)
	@SuppressLint("NewApi")
	private Calendar getCalendarByInintData(String initDateTime) {
		Calendar calendar = Calendar.getInstance();

		// 将初始日期时间2012-07-02 16:45 拆分成年 月 日 时 分 秒
		String[] strs = initDateTime.replaceAll("/", "-").split("\\s+");
		if (null == strs || strs.length != 2) {
			return null;
		}

		String date = strs[0];
		String time = strs[1];

		String yearStr = "";
		String monthStr = "";
		String dayStr = "";

		if (!date.isEmpty()) {
			String[] dateStrs = date.split("-");

			if (dateStrs != null && 3 == dateStrs.length) {
				yearStr = dateStrs[0];
				monthStr = dateStrs[1];
				dayStr = dateStrs[2];
			}
		}

		String hourStr = "";
		String minuteStr = "";
		if (!time.isEmpty()) {
			String[] timeStrs = time.split(":");

			if (timeStrs != null
					&& (2 == timeStrs.length || 3 == timeStrs.length)) {
				hourStr = timeStrs[0];
				minuteStr = timeStrs[1];
			}
		}

		int currentYear = Integer.valueOf(yearStr.trim()).intValue();
		int currentMonth = Integer.valueOf(monthStr.trim()).intValue() - 1;
		int currentDay = Integer.valueOf(dayStr.trim()).intValue();
		int currentHour = Integer.valueOf(hourStr.trim()).intValue();
		int currentMinute = Integer.valueOf(minuteStr.trim()).intValue();

		calendar.set(currentYear, currentMonth, currentDay, currentHour,
				currentMinute);
		return calendar;
	}
}
